package Thread.Safe.volatileKeyword;

import java.util.Scanner;

/**
 *volatile保证共享变量的可见性,不加volatile关键字的情况
 */
public class NonVolatile {
    private static class Counter{
        int flag=0;
    }

    public static void main(String[] args) {
        Counter counter1=new Counter();
        Thread t1=new Thread(()->{
            //t1将flag加载到工作内存后一只读取的是当前工作的内存值，t2的修改堆t1是不可见的
            while (counter1.flag==0){
                //一直循环
            }
            System.out.println(counter1.flag+"退出循环~~");
        },"t1线程~~");
        t1.start();
        Thread t2=new Thread(()->{
            Scanner scanner=new Scanner(System.in);
            System.out.println("请修改flag的值:");
            counter1.flag=scanner.nextInt();
        },"t2线程~~");
        t2.start();
    }
}
